package com.example.jucdemo.synchdemo;

/**
 * @Author: Dijah
 * @Date: 2023/3/17 15:59
 * @Desc:
 * 场景： 两个线程分别同时访问京塔的synchronized 和 非静态的 synchronized
 *  不安全
 *
 *  静态synchronized方法获取的类锁，非静态获取得是对象锁，两个线程拿到的锁是不同的锁，所有不会互相等待，是线程不安全的
 */
public class demo7 implements Runnable{

    static demo7 instance1 = new demo7();
    static demo7 instance2 = new demo7();


    @Override
    public void run() {
        if (Thread.currentThread().getName().equals("Thread-0")){
            method1();
        }
        if (Thread.currentThread().getName().equals("Thread-1")){
            method0();
        }
    }

    // 同步方法
    private synchronized static void method0(){
        System.out.println("线程名" + Thread.currentThread().getName()+",开始运行");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程" + Thread.currentThread().getName() + "运行结束。");
    }

    //普通方法
    public synchronized void method1(){
        System.out.println("线程名" + Thread.currentThread().getName()+",开始运行");
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程" + Thread.currentThread().getName() + ",运行结束");
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(instance1);
        Thread thread2 = new Thread(instance2);
        thread1.start();
        thread2.start();
        while (thread1.isAlive() || thread2.isAlive()){
        }
        System.out.println("测试结束");
    }
}
